package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.service.SearchService;
import com.chaunggou.search.pojo.SkuInfo;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    //设置每页查询条数据
    public final static Integer PAGE_SIZE = 20;
    /**
     * 全文检索
     * @param searchMap
     * @return
     * @throws Exception
     */
    @Override
    public Map search(Map<String, String> searchMap) throws Exception {

        Map<String,Object> resultMap = new HashMap<>();

        //有条件查询ES
        if (resultMap != null){
            //组合条件对象
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            // 0. 关键词
            if (StringUtils.isNotEmpty(searchMap.get("keywords"))){
                boolQuery.must(QueryBuilders.matchQuery("name",searchMap.get("keywords")).operator(Operator.AND));
            }

            //1. 条件品牌
            if (StringUtils.isNotEmpty(searchMap.get("brand"))){
                boolQuery.filter(QueryBuilders.termQuery("brandName",searchMap.get("brand")));
            }

            // 2. 条件规格
            for (String key : searchMap.keySet()) {
                if (key.startsWith("spec_")){
                    String value = searchMap.get(key).replace("%2B","+");
                    boolQuery.filter(QueryBuilders.termQuery("specMap." + key.substring(5) + ".keyword",value));
                }
            }

            // 3. 条件价格
            if (StringUtils.isNotEmpty(searchMap.get("price"))){
                String[] prices = searchMap.get("price").split("-");
                if (prices.length == 2){
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                    boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
                }
            }

            //原生搜索实现类
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQuery);

            // 规格聚合(分组)查询
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //品牌聚合(分组)查询
            String skuBrand = "skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //开启分页查询
            String pageNum = searchMap.get("pageNum"); // 当前页
            String pageSize = searchMap.get("pageSize"); // 每页显示多少条
            if (StringUtils.isEmpty(pageNum)){
                pageNum = "1";
            }
            if (StringUtils.isEmpty(pageSize)){
                pageSize = "30";
            }

            /*
            设置分页
            第一个参数: 当前页 是从0开始
            第二个参数: 每页显示多少条
             */
            // 第一个参数表示第N页,索引从0开始,第二个参数表示每页显示多少条
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1 ,Integer.parseInt(pageSize)));


            //按照相关字段进行排序查询
            // 1. 当前域 2. 当前的排序操作(升序ASC,降序DESC)
            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))){
                if ("ASC".equals(searchMap.get("sortRule"))){
                    //升序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.ASC));
                }else {
                    //降序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.DESC));
                }
            }

            //设置高亮域以及高亮的样式
            HighlightBuilder.Field field = new HighlightBuilder.Field("name") // 高亮域
                    .preTags("<span style='color:red'>") // 高亮样式的前缀
                    .postTags("</span>"); //高亮样式的后缀
            nativeSearchQueryBuilder.withHighlightFields(field);

            //执行查询,返回结果对象
                AggregatedPage<SkuInfo> aggregatedPage = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    //查询结果数据
                    List<T> list = new ArrayList<>();
                    //获取查询命中结果数据
                    SearchHits hits = searchResponse.getHits();

                    if (hits != null){
                        //有结果查询
                        for (SearchHit hit : hits) {
                            // SearchHit 转换为 SkuInfo
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);

                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (highlightFields != null && highlightFields.size() > 0 ){
                                //替换数据
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }

                            list.add((T)skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<T>(list,pageable,hits.getTotalHits(),searchResponse.getAggregations());
                }
            });

            //总条数
            resultMap.put("total",aggregatedPage.getTotalElements());
            //总页数
            resultMap.put("totalPages",aggregatedPage.getTotalPages());
            //查询结果集合
            resultMap.put("rows",aggregatedPage.getContent());

            //获取品牌聚合效果
            StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList",brandList);


            //获取规格聚合结果
            StringTerms specTerms = (StringTerms) aggregatedPage.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList",this.formartSpec(specList));


            //当前页
            resultMap.put("pageNum",pageNum);
            return resultMap;
    }

        return null;
    }

    /**
     *商品属性及规格显示
     */
    public Map<String, Set<String>> formartSpec(List<String> specList){
//       创建map集合, 里面值为 Set 集合(去除重复),
        Map<String,Set<String>> resultMap = new HashMap<>();
        //判断specList 不为null ,  size 大于0
        if (specList != null && specList.size() > 0){
            //遍历specList  specJsonString('颜色':'蓝色','版本':'6GB+128GB')
            for (String specJsonString : specList) {
                //将获取的json转为map
                Map<String,String> specMap = JSON.parseObject(specJsonString,Map.class);
                for (String speckey : specMap.keySet()) {
                    Set<String> specSet = resultMap.get(speckey);
                    if (specSet == null){
                        specSet = new HashSet<>();
                    }

                    //将规格信息存入到set中
                    specSet.add(specMap.get(speckey));

                    //将set存入到map中
                    resultMap.put(speckey,specSet);
                }
            }
        }
        return resultMap;
    }
}
